package erlwitch.gui;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JScrollPane;

import org.gjt.sp.jedit.Buffer;
import org.gjt.sp.jedit.View;
import org.gjt.sp.jedit.jEdit;
import org.gjt.sp.jedit.io.VFSManager;
import org.gjt.sp.jedit.textarea.Selection;

import erlwitch.parser.structure.Function;
import erlwitch.project.SourceFile;

public class FunctionList extends JScrollPane {

	private static final long serialVersionUID = 1L;
	private View view;
	private JList flist;
	private DefaultListModel listModel;

	public FunctionList(View view) {
		this.view = view;
		listModel = new DefaultListModel();
		flist = new JList(listModel);
		getViewport().setView(flist);
		MouseListener mouseListener = new MouseAdapter() {
		    public void mouseClicked(MouseEvent e) {
		        if (e.getClickCount() == 2) {
		            int index = flist.locationToIndex(e.getPoint());
		            SourceLine sl = (SourceLine)flist.getModel().getElementAt(index);
		            gotoSourceLine(sl.getLine(), sl.getSourceFile());
		         }
		    }
		};
		flist.addMouseListener(mouseListener);
	}

	public void gotoSourceLine(final int charNum, String source) {
		final Buffer buffer;
		buffer = jEdit.openFile(view, source);
		if(buffer == null)
			return;

		VFSManager.runInAWTThread(new Runnable() {
			public void run() {
				view.goToBuffer(buffer);

//				int start = 0;
//				int end = 0;
//
//				int lineNo = line - 1;
//				
//				if(lineNo >= 0 && lineNo < buffer.getLineCount()) {
//					start += buffer.getLineStartOffset(lineNo);
//					if(end == 0)
//						end = buffer.getLineEndOffset(lineNo) - 1;
//					else
//						end += buffer.getLineStartOffset(lineNo);
//				}

				view.getTextArea().setCaretPosition(charNum);
			}
		});
	}

	public void clear() {
		listModel.removeAllElements();
	}

	public void updateList(SourceFile srcFile) {
		listModel.removeAllElements();
		for (Function f: srcFile.getModule().getFunList()) {
			listModel.addElement(new SourceLine(
				srcFile.getFile().getAbsolutePath(),
				f.getCharFrom(), 
				f.getNameArity())
			);
		}
	}

}
